﻿using System;
using System.IO;
using System.Xml;
using System.Web;
using SyCODE.Component.DataFactory;
using System.Collections.Specialized;
using System.Net;
using SyCODE.Component.Security;
using SyCODE.Component.Cryptography;
using SyCODE.Component;
using System.Web.Security;

/// <summary>
/// SyCODE 的摘要说明
/// </summary>
namespace SyCODE.Blog
{

    /// <summary>
    /// PostComment.aspx 的POST访问处理程序
    /// </summary>
    public class PostComment : IHttpHandler
    {
        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            NameValueCollection nvc = new NameValueCollection(context.Request.Form);
            string crcode = nvc["crcode"];
            //检测验证码
            if (crcode != null && context.Request.Cookies["comment"] != null && MD5.Encrypt(crcode.ToUpper()) == context.Request.Cookies["comment"].Value)
            {
                nvc.Add("source", "");

                //检测是登录用户还是游客
				Ticket ticket = Ticket.Get(FormsAuthentication.FormsCookieName);
                if (Ticket.Authenticate(ticket))
                {
                    nvc.Set("source", ticket.Name);
                    nvc.Set("sign", HttpUtility.HtmlDecode(ticket.UserData));
                }
                else if (nvc["sign"].Trim().Length < 1)
                {
                    nvc.Set("sign", StringResource.GetField("anonymous"));
                }

                DBAM dbam = new DBAM();
                dbam.BuildParameters("postcomment", nvc);
                try
                {
                    if (dbam.Execute() > 0)
                    {
                        //如果评论发表成功添加最新评论静态文档更新任务

                        float count = (int)dbam.GetResult();

                        nvc.Add("page", ((int)Math.Ceiling(count / 30.0f)).ToString());

                        Task.Processor.Assign(new Task.CommentTask(nvc));
                        context.Response.Write("0");
                    }
                    else
                    {
                        context.Response.Write("1");
                    }
                }
                catch
                {
                    context.Response.Write("2");
                }
                finally
                {
                    dbam.Dispose();
                }
            }
            else
            {
                context.Response.Write("3");
            }
        }
    }
}